//
//  DHShoppingCartViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/14.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHShoppingCartViewController.h"
#import "DHS2_PreOrderController.h"
#import "DHS2_BuyMemberController.h"
#import "DHCart_LeasedCell.h"
#import "DHCart_PurchasedCell.h"
#import "DHCart_WashingCell.h"

@interface DHShoppingCartViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet DHGradualButton *ensureButton;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *noDataLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewBottomLayout;

@property (strong, nonatomic) NSMutableArray *leasedArr;
@property (strong, nonatomic) NSMutableArray *purchasedArr;
@property (strong, nonatomic) NSMutableArray *washedArr;

@property (strong, nonatomic) NSMutableArray *selectedLeasedArr;
@property (strong, nonatomic) NSMutableArray *selectedPurchasedArr;
@property (strong, nonatomic) NSMutableArray *selectedWashingArr;

@end

@implementation DHShoppingCartViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [self loadCartData];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [self.selectedLeasedArr removeAllObjects];
    [self.selectedPurchasedArr removeAllObjects];
    [self.selectedWashingArr removeAllObjects];

    [self.leasedArr removeAllObjects];
    [self.purchasedArr removeAllObjects];
    [self.washedArr removeAllObjects];

}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.bottomViewBottomLayout.constant = self.tabBarController.tabBar.height;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationView setTitleWithString:@"购物车"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHCart_LeasedCell" bundle:nil] forCellReuseIdentifier:kDHCart_LeasedCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHCart_PurchasedCell" bundle:nil] forCellReuseIdentifier:kDHCart_PurchasedCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHCart_WashingCell" bundle:nil] forCellReuseIdentifier:kDHCart_WashingCell];
    self.tableView.mj_header = [DHMJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadCartData)];
}

- (void)loadCartData{
    [[DHNetAPIClient shareDHNetAPIClient] request_cartAndBlock:^(id data, NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.leasedArr removeAllObjects];
         [self.purchasedArr removeAllObjects];
        [self.washedArr removeAllObjects];
        [self.selectedLeasedArr removeAllObjects];
        [self.selectedPurchasedArr removeAllObjects];
        [self.selectedWashingArr removeAllObjects];
        
        [self.leasedArr addObjectsFromArray:[data objectForKey:@"leased"]];
        [self.purchasedArr addObjectsFromArray:[data objectForKey:@"purchased"]];
        [self.washedArr addObjectsFromArray:[data objectForKey:@"washing"]];
        
        [self.tableView reloadData];
        if (self.leasedArr.count > 0 || self.purchasedArr.count > 0 || self.washedArr.count > 0) {
            self.noDataLabel.hidden = YES;
        }
        if (self.leasedArr.count == 0 && self.purchasedArr.count == 0 && self.washedArr.count == 0) {
            self.bottomView.hidden = YES;
        }else{
            self.bottomView.hidden = NO;
        }
        
        [self.leasedArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.selectedLeasedArr addObject:obj];
        }];
        [self.purchasedArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.selectedPurchasedArr addObject:obj];
        }];
        [self.washedArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.selectedWashingArr addObject:obj];
        }];
        
        if (self.leasedArr.count == 0 && self.purchasedArr.count == 0 && self.washedArr.count == 0) {
            self.noDataLabel.hidden = NO;
            self.bottomView.hidden = YES;
        }else{
            self.bottomView.hidden = NO;
        }

        
        [self showTotalPrice];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    if ([eventName isEqualToString:@"leased_selected"]) {
        if ([[userInfo objectForKey:@"selected"] boolValue]) {
            [self.selectedLeasedArr addObject:[userInfo objectForKey:@"item"]];
        }else{
            [self.selectedLeasedArr removeObject:[userInfo objectForKey:@"item"]];
        }
        [self showTotalPrice];
    }else if ([eventName isEqualToString:@"purchased_selected"]){
        if ([[userInfo objectForKey:@"selected"] boolValue]) {
            [self.selectedPurchasedArr addObject:[userInfo objectForKey:@"item"]];
        }else{
            [self.selectedPurchasedArr removeObject:[userInfo objectForKey:@"item"]];
        }
        [self showTotalPrice];
    }else if ([eventName isEqualToString:@"washing_selected"]){
        if ([[userInfo objectForKey:@"selected"] boolValue]) {
            [self.selectedWashingArr addObject:[userInfo objectForKey:@"item"]];
        }else{
            [self.selectedWashingArr removeObject:[userInfo objectForKey:@"item"]];
        }
        [self showTotalPrice];
    }else if ([eventName isEqualToString:@"change_count"]){
        [self loadCartData];
    }else if ([eventName isEqualToString:@"purchased_delete"]){
        NSDictionary *dic = [userInfo objectForKey:@"item"];
        [[DHNetAPIClient shareDHNetAPIClient] request_cart_deleteWithParams:@{@"cart_ids":@[[dic objectForKey:@"cart_id"]]} andBlock:^(id data, NSError *error) {
            [self loadCartData];
        }];
    }else if ([eventName isEqualToString:@"washing_delete"]){
        NSDictionary *dic = [userInfo objectForKey:@"item"];
        [[DHNetAPIClient shareDHNetAPIClient] request_cart_deleteWithParams:@{@"cart_ids":@[[dic objectForKey:@"cart_id"]]} andBlock:^(id data, NSError *error) {
            [self loadCartData];
        }];
    }else if ([eventName isEqualToString:@"leased_delete"]){
        [self loadCartData];
    }
}

// 确定预览订单
- (IBAction)previewOrderAction:(id)sender {
    if (self.selectedLeasedArr.count == 0 && self.selectedPurchasedArr.count == 0 && self.selectedWashingArr.count == 0) {
        [NSObject showHudTipStr:@"请选择商品"];
        return;
    }
    NSMutableArray *sizeIDArr = [NSMutableArray array];
    NSMutableArray *purchasedIDArr = [NSMutableArray array];
    NSMutableArray *washingIDArr = [NSMutableArray array];
    [self.selectedLeasedArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [sizeIDArr addObject:@{@"size_id":obj[@"size_id"],@"count":@(1)}];
    }];
    [self.selectedPurchasedArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSUInteger count = [[obj objectForKey:@"count"] integerValue];
        [purchasedIDArr addObject:@{@"size_id":obj[@"size_id"],@"count":@(count)}];
    }];
    [self.selectedWashingArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSUInteger count = [[obj objectForKey:@"count"] integerValue];
        [washingIDArr addObject:@{@"category_id":obj[@"category_id"],@"count":@(count)}];
    }];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (sizeIDArr.count > 0) {
        [params setObject:sizeIDArr forKey:@"subscribed"];
    }
    if (purchasedIDArr.count > 0) {
        [params setObject:purchasedIDArr forKey:@"purchased"];
    }
    if (washingIDArr.count > 0) {
        [params setObject:washingIDArr forKey:@"washing"];
    }
    if (self.selectedLeasedArr.count > 0 && ![GlobalManager shareGlobalManager].vip.vip) {
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"您当前还不是会员，是否需要购买会员？" cancelButtonTitle:@"否" otherButtonTitles:@[@"是"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                DHS2_BuyMemberController *buyController = [[DHS2_BuyMemberController alloc] init];
                self.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:buyController animated:YES];
                self.tabBarController.tabBar.hidden = YES;
                
            }
        }];
    }else{
        [[DHNetAPIClient shareDHNetAPIClient] request_order_precreateWithParams:params andBlock:^(id data, NSError *error) {
            if (data) {
                DHS2_PreOrderController *odController = [[DHS2_PreOrderController alloc] init];
                odController.orderId = [[data objectForKey:@"order"] objectForKey:@"_id"];
                //                    odController.cartSelectedArr = self.selectedProductArr;
                //                    odController.cartSlectedSizesArr = self.selectedSizesArr;
                [self.navigationController pushViewController:odController animated:YES];
                self.tabBarController.tabBar.hidden = YES;
            }
        }];
    }
}

#pragma mark - UITableViewDelegate and UITableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        if (self.leasedArr.count > 0) {
            return self.leasedArr.count * 100 + 50;
        }else{
            return 0;
        }
    }else if (indexPath.row == 1){
        if (self.purchasedArr.count > 0) {
            return self.purchasedArr.count * 100 + 50;
        }else{
            return 0;
        }
    }else{
        if (self.washedArr.count > 0) {
            return self.washedArr.count * 100 + 50;
        }else{
            return 0;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        DHCart_LeasedCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHCart_LeasedCell forIndexPath:indexPath];
//        if (indexPath.section == 0) {
//            NSDictionary *dic = [self.leasedArr objectAtIndex:indexPath.row];
//            if ([self.selectedLeasedArr containsObject:dic]) {
//                [cell.selectedButton setImage:[UIImage imageNamed:@"cart_selected.png"] forState:UIControlStateNormal];
//                cell.itemSelected = YES;
//            }else{
//                [cell.selectedButton setImage:[UIImage imageNamed:@"cart_unselected.png"] forState:UIControlStateNormal];
//                cell.itemSelected = NO;
//            }
//            [cell updateCell:dic];
//        }
        [cell updateCellArr:self.leasedArr selectedArr:self.selectedLeasedArr];
        if (self.leasedArr.count == 0) {
            cell.contentView.hidden = YES;
        }else{
            cell.contentView.hidden = NO;
        }
        return cell;
    }else if (indexPath.row == 1){
        DHCart_PurchasedCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHCart_PurchasedCell forIndexPath:indexPath];
//        NSDictionary *dic = [self.purchasedArr objectAtIndex:indexPath.row];
//        if ([self.selectedPurchasedArr containsObject:dic]) {
//            [cell.selectedButton setImage:[UIImage imageNamed:@"cart_selected.png"] forState:UIControlStateNormal];
//            cell.itemSelected = YES;
//        }else{
//            [cell.selectedButton setImage:[UIImage imageNamed:@"cart_unselected.png"] forState:UIControlStateNormal];
//            cell.itemSelected = NO;
//        }
//        [cell updateCell:dic];
        [cell updateCellArr:self.purchasedArr selectedArr:self.selectedPurchasedArr];
        if (self.purchasedArr.count == 0) {
            cell.contentView.hidden = YES;
        }else{
            cell.contentView.hidden = NO;
        }
        return cell;
    }else{
        DHCart_WashingCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHCart_WashingCell forIndexPath:indexPath];
//        NSDictionary *dic = [self.washedArr objectAtIndex:indexPath.row];
//        [cell updateCell:dic];
//        if ([self.selectedWashingArr containsObject:dic]) {
//            [cell.selectedButton setImage:[UIImage imageNamed:@"cart_selected.png"] forState:UIControlStateNormal];
//            cell.itemSelected = YES;
//        }else{
//            [cell.selectedButton setImage:[UIImage imageNamed:@"cart_unselected.png"] forState:UIControlStateNormal];
//            cell.itemSelected = NO;
//        }
        [cell updateCellArr:self.washedArr selectedArr:self.selectedWashingArr];
        if (self.washedArr.count == 0) {
            cell.contentView.hidden = YES;
        }else{
            cell.contentView.hidden = NO;
        }
        return cell;
    }
}

//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        NSDictionary *dic;
//        if (indexPath.section == 0) {
//            dic = [self.leasedArr objectAtIndex:indexPath.row];
//            [[DHNetAPIClient shareDHNetAPIClient] request_cart_deleteWithParams:@{@"cart_ids":@[[dic objectForKey:@"cart_id"]]} andBlock:^(id data, NSError *error) {
//                [[GlobalManager shareGlobalManager] refreshCartNumberAndBlock:^(id data, NSError *error) {
//                    [self.leasedArr removeObjectAtIndex:indexPath.row];
//                    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
//                    if (self.leasedArr.count == 0 && self.purchasedArr.count == 0 && self.washedArr.count == 0) {
//                        self.noDataLabel.hidden = NO;
//                        self.bottomView.hidden = YES;
//                    }else{
//                        self.bottomView.hidden = NO;
//                    }
//                }];
//            }];
//        }else if (indexPath.section == 1){
//            dic = [self.purchasedArr objectAtIndex:indexPath.row];
//            [[DHNetAPIClient shareDHNetAPIClient] request_cart_deleteWithParams:@{@"cart_ids":@[[dic objectForKey:@"cart_id"]]} andBlock:^(id data, NSError *error) {
//                [[GlobalManager shareGlobalManager] refreshCartNumberAndBlock:^(id data, NSError *error) {
//                    [self.purchasedArr removeObjectAtIndex:indexPath.row];
//                    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
//                    if (self.leasedArr.count == 0 && self.purchasedArr.count == 0 && self.washedArr.count == 0) {
//                        self.noDataLabel.hidden = NO;
//                        self.bottomView.hidden = YES;
//                    }else{
//                        self.bottomView.hidden = NO;
//                    }
//                }];
//            }];
//        }else if (indexPath.section == 2){
//            dic = [self.washedArr objectAtIndex:indexPath.row];
//            [[DHNetAPIClient shareDHNetAPIClient] request_cart_deleteWithParams:@{@"cart_ids":@[[dic objectForKey:@"cart_id"]]} andBlock:^(id data, NSError *error) {
//                [[GlobalManager shareGlobalManager] refreshCartNumberAndBlock:^(id data, NSError *error) {
//                    [self.washedArr removeObjectAtIndex:indexPath.row];
//                    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
//                    if (self.leasedArr.count == 0 && self.purchasedArr.count == 0 && self.washedArr.count == 0) {
//                        self.noDataLabel.hidden = NO;
//                        self.bottomView.hidden = YES;
//                    }else{
//                        self.bottomView.hidden = NO;
//                    }
//                }];
//            }];
//        }
//    }
//}
//
//- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return @"删除";
//}

- (void)showTotalPrice{
    __block CGFloat totalPrice = 0.00;
    [self.selectedLeasedArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj) {
            CGFloat lease_price = [[obj objectForKey:@"lease_price"] floatValue];
            totalPrice += lease_price;
        }
    }];
    [self.selectedPurchasedArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj) {
            CGFloat lease_price = [[obj objectForKey:@"sales_price"] floatValue];
            NSInteger count = [[obj objectForKey:@"count"] integerValue];
            totalPrice += lease_price * count;
        }
    }];
    [self.selectedWashingArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj) {
            CGFloat lease_price = [[obj objectForKey:@"wash_price"] floatValue];
            NSInteger count = [[obj objectForKey:@"count"] integerValue];
            totalPrice += lease_price * count;
        }
    }];
    self.priceLabel.text = [NSString stringWithFormat:@"合计:￥%.2f",totalPrice];
}

#pragma mark - arr
- (NSMutableArray *)leasedArr{
    if (!_leasedArr) {
        _leasedArr = [NSMutableArray array];
    }
    return _leasedArr;
}

- (NSMutableArray *)purchasedArr{
    if (!_purchasedArr) {
        _purchasedArr = [NSMutableArray array];
    }
    return _purchasedArr;
}

- (NSMutableArray *)washedArr{
    if (!_washedArr) {
        _washedArr = [NSMutableArray array];
    }
    return _washedArr;
}

- (NSMutableArray *)selectedLeasedArr{
    if (!_selectedLeasedArr) {
        _selectedLeasedArr = [NSMutableArray array];
    }
    return _selectedLeasedArr;
}

- (NSMutableArray *)selectedPurchasedArr{
    if (!_selectedPurchasedArr) {
        _selectedPurchasedArr = [NSMutableArray array];
    }
    return _selectedPurchasedArr;
}

- (NSMutableArray *)selectedWashingArr{
    if (!_selectedWashingArr) {
        _selectedWashingArr = [NSMutableArray array];
    }
    return _selectedWashingArr;
}

@end
